package com.splic.product.service.impl;

import cn.hutool.core.date.DateUtil;
import com.splic.common.core.DeviceContext;
import com.splic.common.exception.BusinessException;
import com.splic.common.utils.DateUtils;
import com.splic.common.utils.ShiroUtils;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.Product;
import com.splic.product.domain.User;
import com.splic.product.domain.Work;
import com.splic.product.mapper.WorkMapper;
import com.splic.product.service.ProductService;
import com.splic.product.service.UserService;
import com.splic.product.service.WorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 事件同步Service业务层处理
 * 
 * @author singe
 * @date 2023-06-18
 */
@Service
public class WorkServiceImpl implements WorkService
{
    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private ProductService productServiceImpl;

    @Autowired
    private UserService userService;

    /**
     * 查询事件同步
     * 
     * @param id 事件同步主键
     * @return 事件同步
     */
    @Override
    public Work selectWorkById(Long id)
    {
        return workMapper.selectWorkById(id);
    }

    /**
     * 查询事件同步列表
     * 
     * @param work 事件同步
     * @return 事件同步
     */
    @Override
    public List<Work> selectPageList(Work work)
    {
        return workMapper.selectWorkList(work);
    }

    /**
     * 查询事件同步列表
     *
     * @param work 事件同步
     * @return 事件同步
     */
    @Override
    public List<Work> selectWorkList(Work work)
    {
        if (StringUtils.isEmpty(work.getStartCreateTime())) {
            work.setStartCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), -7)));
        }
        if (StringUtils.isEmpty(work.getEndCreateTime())) {
            work.setEndCreateTime(DateUtil.formatDate(DateUtil.offsetDay(new Date(), 1)));
        } else {
            work.setEndCreateTime(DateUtil.formatDate(DateUtil.offsetDay(DateUtils.parseDate(work.getEndCreateTime()), 1)));
        }
        return workMapper.selectWorkList(work);
    }

    /**
     * 新增事件同步
     * 
     * @param work 事件同步
     * @return 结果
     */
    @Override
    public int insert(Work work)
    {
        work.setCreateTime(DateUtils.getNowDate());
        return workMapper.insert(work);
    }

    /**
     * 修改事件同步
     * 
     * @param work 事件同步
     * @return 结果
     */
    @Override
    public int update(Work work)
    {
        work.setUpdateTime(DateUtils.getNowDate());
        return workMapper.update(work);
    }


    /**
     * 删除事件同步信息
     * 
     * @param id 事件同步主键
     * @return 结果
     */
    @Override
    public int deleteById(Long id)
    {
        return workMapper.deleteById(id);
    }
    /**
     * 修改事件同步
     *
     * @param work 事件同步信息
     * @return 结果
     */
    @Override
    @Transactional
    public int saveOrUpdate(Work work)
    {
        if(work.getId() != null){
            work.setUpdateTime(new Date());
            return workMapper.update(work);
        }else{
            work.setCreateTime(new Date());
            return workMapper.insert(work);
        }
    }

    @Override
    public Work judgeSync(Work workReq) {
        Work work = new Work();
        Long userId = ShiroUtils.getUserId();
        String deviceId = DeviceContext.getDeviceIdentify();
        String packageKey = DeviceContext.getProductPackageKey();
        Product product = productServiceImpl.getByPackageKey(packageKey);
        if (deviceId == null || userId == null || product == null) {
            work.setReturnCode(-1);
            work.setReturnMsg("缺少必要参数");
            return work;
        }
        User user = userService.selectUserById(userId);
        if (user == null) {
            work.setReturnCode(-1);
            work.setReturnMsg("用户不存在");
            return work;
        }
        work = workMapper.selectWorkByWorkId(workReq.getWorkId());
        if (work != null) {
            work.setStatus(StringUtils.isEmpty(workReq.getStatus()) ? "2" : workReq.getStatus());
            work.setUpdateTime(new Date());
            work.setFailMsg(workReq.getFailMsg());
            workMapper.update(work);
        }

        workReq.setUserId(user.getUserIdentify());
        workReq.setProductId(product.getId());
        work = workMapper.selectWorkByUserId(workReq);
        if (work == null) {
            return createWork(user.getUserIdentify(), deviceId, workReq.getUnionId(), product.getId(), product.getName());
        } else {
            if (work.getDeviceId().equals(deviceId)) {
                work.setStatus(StringUtils.isEmpty(workReq.getStatus()) ? "2" : workReq.getStatus());
                work.setUpdateTime(new Date());
                work.setFailMsg(workReq.getFailMsg());
                workMapper.update(work);
                return createWork(user.getUserIdentify(), deviceId, workReq.getUnionId(), product.getId(), product.getName());
            } else {
                work.setReturnCode(-1);
                work.setReturnMsg("您有其他设备正在同步中");
                return work;
            }
        }
    }

    @Override
    public int finishSync(Work workReq) {
        Work work = workMapper.selectWorkByWorkId(workReq.getWorkId());
        if (work == null) {
            throw new BusinessException("不存在的事件", -100);
        } else {
            work.setStatus(workReq.getStatus());
            work.setFailMsg(workReq.getFailMsg());
            work.setUpdateTime(new Date());
            return workMapper.update(work);
        }
    }

    private Work createWork(String userIdentify, String deviceId, String unionId, Long productId, String productName){
        Work work = new Work();
        work.setWorkId(System.currentTimeMillis());
        work.setUserId(userIdentify);
        work.setDeviceId(deviceId);
        work.setUnionId(unionId);
        work.setProductId(productId);
        work.setProductName(productName);
        work.setStatus("0");
        work.setCreateTime(new Date());
        int result = workMapper.insert(work);
        if (result == 1) {
            work.setReturnCode(1);
            return work;
        } else {
            work.setReturnCode(-1);
            work.setReturnMsg("事件同步记录异常");
            return work;
        }
    }
}
